package com.heima.account.handler;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heima.commons.enums.BusinessErrors;
import com.heima.commons.exception.BusinessRuntimeException;
import com.heima.modules.po.VehiclePO;
import okhttp3.*;
import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

@Component
public class AiHelper {
    @Value("${baidu.apikey}")
    private String API_KEY;
    @Value("${baidu.secretkey}")
    private String SECRET_KEY;

    private final static Logger logger = LoggerFactory.getLogger(AiHelper.class);

    final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();


    public static void main(String []args) throws IOException {
        String code = new AiHelper().getLicense(null);
        System.out.println(code);
    }

    /*

    图像识别，获取车牌信息
    文档（行驶证识别）：https://cloud.baidu.com/doc/OCR/s/yk3h7y3ks
    文档（车牌识别）：https://cloud.baidu.com/doc/OCR/s/ck3h7y191
    获取车辆照片url
    将url下载到某个临时文件夹
    将文件编码为base64
    调百度AI接口，返回对应信息
    对比：行驶证车牌 和 车辆车牌是否一致
    如果一致，设置车牌信息，认证通过，身份变更为车主

    简化版业务流程（至少完成）：识别车辆车牌号即可

    * */
    public String getLicense(VehiclePO vehiclePO) throws IOException {
        if (vehiclePO == null || vehiclePO.getCarFrontPhoto() == null) {
            throw new BusinessRuntimeException(BusinessErrors.PARAM_CANNOT_EMPTY);
        }

        // 下载图片到临时文件
        String imageUrl = vehiclePO.getCarFrontPhoto();
        String tempDir = System.getProperty("java.io.tmpdir");
        String fileName = "car_front_" + System.currentTimeMillis() + ".jpg";
        File file = new File(tempDir, fileName);

        try (Response response = HTTP_CLIENT.newCall(new Request.Builder().url(imageUrl).build()).execute()) {
            if (!response.isSuccessful()) {
                throw new BusinessRuntimeException(BusinessErrors.PARAM_CANNOT_EMPTY);
            }

            ResponseBody body = response.body();
            if (body == null) {
                throw new BusinessRuntimeException(BusinessErrors.PARAM_CANNOT_EMPTY);
            }

            byte[] imageBytes = body.bytes();
            Files.write(file.toPath(), imageBytes);
        }

        // 将图片编码为Base64
        byte[] fileBytes = Files.readAllBytes(file.toPath());
        String encodedImage = Base64.getEncoder().encodeToString(fileBytes);

        // 构建请求参数
        JSONObject json = new JSONObject();
        json.put("image", encodedImage);
        json.put("detect_direction", "true");
        json.put("accuracy", "normal");

        // 获取百度AI接口的token
        String getTokenUrl = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="
                + API_KEY + "&client_secret=" + SECRET_KEY;
        String tokenResponse = HTTP_CLIENT.newCall(new Request.Builder().url(getTokenUrl).get().build()).execute().body().string();
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(tokenResponse);
        String accessToken = jsonNode.get("access_token").asText();

        // 调用百度OCR接口识别车牌号
        String ocrUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate";
        RequestBody requestBody = RequestBody.create(MediaType.get("application/x-www-form-urlencoded"), 
                "access_token=" + accessToken + "&image=" + URLEncoder.encode(encodedImage, "UTF-8"));
        Request request = new Request.Builder()
                .url(ocrUrl)
                .post(requestBody)
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String ocrResponse = response.body().string();

        // 解析OCR结果
        JsonNode ocrResult = objectMapper.readTree(ocrResponse);
        JsonNode wordsResult = ocrResult.get("words_result");
        if (wordsResult == null || !wordsResult.isArray() || wordsResult.size() == 0) {
            throw new BusinessRuntimeException(BusinessErrors.DATA_NOT_EXIST, "OCR识别结果为空，无法获取车牌信息");
        }

        JsonNode plateNumberNode = wordsResult.get(0).get("number");
        if (plateNumberNode == null) {
            throw new BusinessRuntimeException(BusinessErrors.DATA_NOT_EXIST, "OCR识别结果为空，无法获取车牌信息");
        }

        String plateNumber = plateNumberNode.asText();

        // 删除临时文件
        Files.deleteIfExists(file.toPath());

        // 设置车牌号并更新车辆信息
        vehiclePO.setCarNumber(plateNumber);
        // 这里应该调用相应的service方法保存更新后的vehiclePO，但当前方法没有传入service，所以暂时不保存

        return plateNumber;
    }

}
